package com.cqut.forum.controller;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cqut.forum.entity.Academy;
import com.cqut.forum.entity.Message;
import com.cqut.forum.entity.User;
import com.cqut.forum.service.IAcademyService;
import com.cqut.forum.service.IMessageService;
import com.cqut.forum.service.IUserService;
import com.cqut.forum.util.ConfigProperties;
import com.cqut.forum.util.CookieHandler;
import com.cqut.forum.util.DESUtils;
import com.cqut.forum.util.DateUtil;
import com.cqut.forum.util.DefaultElements;
import com.cqut.forum.util.Encode64;
import com.cqut.forum.util.SendMailHandler;
import com.cqut.forum.util.StringUtil;

/**
 * @author 刘强webControllerContext.xml
 *
 */
@Controller
@RemoteProxy(name = "userRemoting")  
public class UserController {
	Map<String,Object> root=new HashMap<String, Object>();
	private static Log log = LogFactory.getLog(UserController.class);
	
	private IUserService userService;
	private IAcademyService academyService;
	private IMessageService messageService;

	public IUserService getUserService() {
		return userService;
	}
	@Autowired  
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	public IAcademyService getAcademyService() {
		return academyService;
	}
	@Autowired 
	public void setAcademyService(IAcademyService academyService) {
		this.academyService = academyService;
	}
	
	public IMessageService getMessageService() {
		return messageService;
	}
	public void setMessageService(IMessageService messageService) {
		this.messageService = messageService;
	}
	/**
	* @author 刘强
	* @Title: loginView
	* @Description: 登录页面
	* @return String
	* @date 2015年4月21日 下午4:31:33
	*/ 
	@RequestMapping(value="/login.do")
	public String login(HttpServletRequest request,HttpServletResponse response){
		//如果用户已登录，则返回index页面
		String cookieValue=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);
		if(null!=cookieValue){
			  return  "redirect:index.do";
		}
		return "/home/login";
	}
	/**
	* @author 刘强
	* @Title: login
	* @Description: 登录处理
	* @return String    
	* @date 2015年4月21日 下午4:53:50
	*/ 
	@RemoteMethod
	public int loginJson(String email,String password){
		//base64解密
		email=new String(Encode64.decode(email));
		password=new String(Encode64.decode(password));
		
		HttpServletResponse response=WebContextFactory.get().getHttpServletResponse();
		int result=0;
		User user=userService.getUserByEmailAndPassword(email, password);
		if(null!=user){
			if(user.getIsfrozen()==0){
				result=1;	
				CookieHandler.setCookie(response, DefaultElements.COOKIE_NAME, DESUtils.encode(user.getEmail()), DefaultElements.COOKIE_LIFE);
				log.info(user.getEmail()+"登录成功");
			}else{
				result=2;
			}
		}
		return result;
	}
	/**
	* @Title: Regist
	* @Description: 返回注册页面  
	* @return String  
	* @throws
	* @author 刘强   
	* @date 2015-4-24 下午2:13:31
	*/ 
	@RequestMapping(value="/regist.do")
	public String regist(HttpServletRequest request,HttpServletResponse response){
		List<Academy> academys=academyService.getAcademys();
		request.setAttribute("academys", academys);
		return "/home/reg";
	}
	/**
	* @Title: registJson
	* @Description: 注册处理  
	* @return int  0 处理异常   1注册邮箱已存在   2注册验证成功
	* @throws
	* @author 刘强   
	* @date 2015-4-24 下午3:26:38
	*/ 
	@RemoteMethod
	public int registJson(String name,String userId,String academy,String password,String email){
		HttpServletRequest request=WebContextFactory.get().getHttpServletRequest();
		int result=0;
		//如果该注册邮箱不存在
		if(!userService.isExeistEmail(email)){
			User user=new User();
			user.setUserName(name);
			user.setUserId(Long.parseLong(userId));
			user.setAcademyId(Long.parseLong(academy));
			user.setPassword(password);
			user.setEmail(email);	
			user.setCreateDate(DateUtil.getCurrentDate());
			request.getSession().setAttribute(user.getUserId().toString(), user);
			
			String sendEmail=ConfigProperties.get("sendMail");
			String sendEmailPW=ConfigProperties.get("senMailPW");
			String host=ConfigProperties.get("mail.smtp.host");
			String port=ConfigProperties.get("mail.smtp.port");
			StringBuilder content=new StringBuilder();
			String url=ConfigProperties.get("activateRegistHref")+"?id="+user.getUserId();
			content.append("点击<a href=").append(url).append(" target='_blank' >这里</a>，即刻完成注册");
			SendMailHandler.sendMail(host, port, sendEmail, sendEmailPW, user.getEmail(), "注册激活", content.toString());
			result=2;
		}else{
			result=1;
		}
		return result;
	}
	@RequestMapping(value="activateRegist.do")
	public String activateRegist(HttpServletRequest request,HttpServletResponse response){
		String userId=request.getParameter("id");
		StringBuilder result=new StringBuilder();
		User user=(User)request.getSession().getAttribute(userId);
		if(null==user){
			result.append("对不起，").append("您注册失败！");
		}else{
			User user_2=userService.getUserByUserId(user.getUserId());
			if(null==user_2){//如果数据库不存在该用户则可以注册
				userService.save(user);
				result.append("恭喜").append(user.getUserName()).append(",您已完成注册！");
				request.getSession().removeAttribute(user.getUserId().toString());//注册完成  删除session中的保存的user
				Message message=new Message();
				message.setUserId(user.getId());
				message.setTitle(DefaultElements.SIGNSUCCESS);
				message.setContent(DefaultElements.SIGNSUCCESS);
				message.setCreateDate(DateUtil.getCurrentTimestamp());
				message.setType(1);
				messageService.saveMessage(message);
			}else{
				result.append("对不起，").append("该用户已注册！");
			}
		}
		request.setAttribute("result", result);
		return "/home/regResult";
	}
	/**
	* @Title: getUserName
	* @Description: 获取用户名称  
	* @return String  
	* @author 刘强   
	* @date 2015-5-5 上午1:23:04
	*/ 
	@RemoteMethod
	public String getUserName(){
		String result=null;
		HttpServletRequest request=WebContextFactory.get().getHttpServletRequest();
		String cookieName=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);	
		if(null!=cookieName){
			User user=userService.getUserByEmail(DESUtils.decode(cookieName));
			if(null!=user){
				result=user.getUserName();
			}
		}
		return result;		
	}
	/**
	* @Title: logout
	* @Description: 用户退出注销
	* @return int  
	* @author 刘强   
	* @date 2015-5-5 下午12:53:19
	*/ 
	@RemoteMethod
	public int logout(){
		int result=0;
		HttpServletResponse response=WebContextFactory.get().getHttpServletResponse();
		CookieHandler.delCookie(response, DefaultElements.COOKIE_NAME);	
		result=1;
		return result;
	}
	/**
	* @Title: personCenter
	* @Description: 返回用户个人中心页面  
	* @return String  
	* @author 刘强   
	* @date 2015-5-10 下午10:06:47
	*/ 
	@RequestMapping(value="/personCenter.do")
	public String personCenter(HttpServletRequest request,HttpServletResponse response){
		String active=request.getParameter("active");//"1" 加载用户信息页面，2加载消息页面
		request.setAttribute("active", active);
		return "home/personalcenter";
	}
	/**
	* @Title: getUserJson
	* @Description: 返回用户信息  
	* @return void  
	* @author 刘强   
	* @date 2015-5-11 下午1:18:06
	*/ 
	@RequestMapping(value="/getUserJson.do")
	public void getUserJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		User user=null;
		String cookieName=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);	
		if(null!=cookieName){
			user=userService.getUserByEmail(DESUtils.decode(cookieName));
			Academy academy=academyService.getAcademy(user.getAcademyId());
			user.setAcademyName(academy.getAcademyName());
		}
		root.put("user", user);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	 * @Title: getPersoninformation
	 * @Description: 返回  personinformation页面
	 * @return String  
	 * @author 刘强   
	 * @date 2015-5-11 下午10:44:46
	 */ 
	@RequestMapping(value="getPersoninformation.do")
	public String getPersoninformation(HttpServletRequest request,HttpServletResponse response){
		return "home/personinformation";
	}
	/**
	* @Title: getPersonUpdate
	* @Description: 返回  personalupdate页面
	* @return String  
	* @author 刘强   
	* @date 2015-5-11 下午2:18:21
	*/ 
	@RequestMapping(value="getPersonUpdate.do")
	public String getPersonUpdate(HttpServletRequest request,HttpServletResponse response){
		List<Academy> academys=academyService.getAcademys();
		request.setAttribute("academys", academys);
		return "home/personalupdate";
	}
	/**
	* @Title: getPersonModifyWP
	* @Description: 返回密码修改页面  
	* @return String  
	* @author 刘强   
	* @date 2015-5-12 上午1:03:23
	*/ 
	@RequestMapping(value="getPersonModifyWP.do")
	public String getPersonModifyWP(HttpServletRequest request,HttpServletResponse response){
		return "home/personmodifyWP";
	}
	/**
	* @Title: getPersonPost
	* @Description: 返回个人帖子页面  
	* @return String  
	* @author 刘强   
	* @date 2015-5-12 下午2:56:00
	*/ 
	@RequestMapping(value="getPersonPost.do")
	public String getPersonPost(HttpServletRequest request,HttpServletResponse response){
		return "home/personpost";
	}
	@RequestMapping(value="getPersonComment.do")
	public String getPersonComment(HttpServletRequest request,HttpServletResponse response){
		return "home/personcomment";
	}
	@RequestMapping(value="/postMessage.do")
	public String postMessage(HttpServletRequest request,HttpServletResponse response){
		return "home/personpostmessage";
	}
	@RequestMapping(value="/systemMessage.do")
	public String systemMessage(HttpServletRequest request,HttpServletResponse response){
		return "home/personsystemmessage";
	}
	/**
	* @Title: getPersonUpdateJson
	* @Description: 提交修改的用户数据  
	* @return void  
	* @author 刘强   
	* @date 2015-5-12 上午12:22:01
	*/ 
	@RequestMapping(value="getPersonUpdateJson.do")
	public void getPersonUpdateJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String username=request.getParameter("username");
		String role=request.getParameter("role");
		String userid=request.getParameter("userid");
		String email=request.getParameter("email");
		String academyid=request.getParameter("academyid");
		String sex=request.getParameter("sex");
		String birthday=request.getParameter("birthday");
		String phoneNumber=request.getParameter("phoneNumber");
		String nativePlace=request.getParameter("nativePlace");
		String abode=request.getParameter("abode");
		User user=userService.getUserByEmail(email);
		user.setUserName(username);
		user.setRole(role.equals("学生") ? 0 : 1);
		user.setUserId(Long.parseLong(userid));
		user.setAcademyId(Long.parseLong(academyid));
		user.setSex(Integer.parseInt(sex));
		user.setBirthday(birthday);
		user.setPhoneNumber(phoneNumber);
		user.setNativePlace(nativePlace);
		user.setAbode(abode);
		userService.saveOrUpdate(user);
		root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: modifyPasswordJson
	* @Description: 修改密码处理  
	* @return void  
	* @author 刘强   
	* @date 2015-5-12 上午1:32:17
	*/ 
	@RequestMapping(value="modifyPasswordJson.do")
	public void modifyPasswordJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		int result=0;
		String password=request.getParameter("password");
		String newpassword=request.getParameter("newpassword");
		String cookieName=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);	
		User user=userService.getUserByEmail(DESUtils.decode(cookieName));
		if(password.equals(user.getPassword())){
			user.setPassword(newpassword);
			userService.saveOrUpdate(user);
			result=1;
		}else{
			result=-1;
		}
	    root.put("result", result);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: postMessageJson
	* @Description: 获取帖子消息  
	* @return void  
	* @author 刘强   
	* @date 2015-5-16 下午11:48:34
	*/ 
	@RequestMapping(value="/postMessageJson.do")
	public void postMessageJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String page=request.getParameter("page");//当前页
		String cookieValue=DESUtils.decode(CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME));
		User user=userService.getUserByEmail(cookieValue);//获取当前用户
		int pageSize=Integer.parseInt(ConfigProperties.get("personCommentSize"));
		List<Message> lists=messageService.getPostMessage(user.getId(), Integer.parseInt(page), pageSize);
		int total=messageService.getPostMessageTotal(user.getId());
		int rowCount=0;
		if(total%pageSize!=0){
			rowCount = total / pageSize + 1; 
		}else{
			rowCount = total / pageSize; 
		}
		root.put("pageCount", rowCount);
		root.put("CurrentPage", page);
		root.put("list", lists);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: postMessageReader
	* @Description: 帖子消息阅读处理  
	* @return String  
	* @author 刘强   
	* @date 2015-5-17 上午12:18:17
	*/ 
	@RequestMapping(value="/postMessageReader.do")
	public String postMessageReader(HttpServletRequest request,HttpServletResponse response){
		String id=request.getParameter("id");
		Message message=messageService.getMessageById(Long.parseLong(id));
		message.setIsRead(DefaultElements.ONE);
		messageService.update(message);
		return "redirect:postdetail.do?id="+message.getTargetId();
	}
	/**
	* @Title: systemMessageJson
	* @Description: 获取系统消息  
	* @return void  
	* @author 刘强   
	* @date 2015-5-17 上午12:34:21
	*/ 
	@RequestMapping(value="/systemMessageJson.do")
	public void systemMessageJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String page=request.getParameter("page");//当前页
		String cookieValue=DESUtils.decode(CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME));
		User user=userService.getUserByEmail(cookieValue);//获取当前用户
		int pageSize=Integer.parseInt(ConfigProperties.get("personCommentSize"));
		List<Message> lists=messageService.getSystemMessage(user.getId(), Integer.parseInt(page), pageSize);
		int total=messageService.getSystemMessageTotal(user.getId());
		int rowCount=0;
		if(total%pageSize!=0){
			rowCount = total / pageSize + 1; 
		}else{
			rowCount = total / pageSize; 
		}
		root.put("pageCount", rowCount);
		root.put("CurrentPage", page);
		root.put("list", lists);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: systemMessageReader
	* @Description: 系统消息阅读处理 
	* @return void  
	* @author 刘强   
	* @date 2015-5-17 上午12:37:47
	*/ 
	@RequestMapping(value="/systemMessageReader.do")
	public void systemMessageReader(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String id=request.getParameter("id");
		Message message=messageService.getMessageById(Long.parseLong(id));
		message.setIsRead(DefaultElements.ONE);
		messageService.update(message);
		root.put("message", message);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: getUserMessageNum
	* @Description: 获取用户的新的消息数量  
	* @return void  
	* @author 刘强   
	* @date 2015-5-17 上午1:07:38
	*/ 
	@RequestMapping(value="/getUserMessageNum.do")
	public void getUserMessageNum(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String cookieValue=DESUtils.decode(CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME));
		User user=userService.getUserByEmail(cookieValue);//获取当前用户
		int total=messageService.getMessageNum(user.getId());
		root.put("total", total);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: getUserMessageNumForPostAndSystem
	* @Description: 获取帖子和系统的新的消息数量  
	* @return void  
	* @author 刘强   
	* @date 2015-5-17 上午1:07:08
	*/ 
	@RequestMapping(value="/getUserMessageNumForPostAndSystem.do")
	public void getUserMessageNumForPostAndSystem(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String cookieValue=DESUtils.decode(CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME));
		User user=userService.getUserByEmail(cookieValue);//获取当前用户
		int postTotal=messageService.getPostMessageNum(user.getId());
		int systemTotal=messageService.getSystemMessageNum(user.getId());
		root.put("postTotal", postTotal);
		root.put("systemTotal", systemTotal);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	
}